﻿using System;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Text;

namespace sjzyoukucaiji
{
    public class Manage
    {
        private MysqlDB _db;
        public MysqlDB db
        {
            get { return _db ?? (_db = new MysqlDB()); }
        }
        #region 站点地图

        /// <summary>
        /// xml
        /// </summary>
        /// <returns></returns>
        public bool CreateZhanDianXml()
        {
            bool b = false;
            StreamWriter sw = null;
            //生成静态文件
            try
            {
            //    System.Text.Encoding code = System.Text.Encoding.GetEncoding("utf-8");
            //    string str = Creatxmlstring();
            //    string mbPath = @"D:\sjzyoukucaiji\LocalUser\sjzyoukucaiji\Rss.xml";
            //    sw = new StreamWriter(mbPath, false, code);
            //    sw.Write(str);
            //    sw.Flush();
            //    b = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sw.Close();
            }
            return b;
        }
        private string Creatxmlstring()
        {
            var sql = "select max(vid) from ccvms_video";
            var dt = GetDTBySql(sql);
            if (dt.Rows.Count != 1)
                throw new ApplicationException("最大id为获取到");
            var maxid = int.Parse(dt.Rows[0][0].ToString());

            string pindaosql = "select cid as pindaoid,htmlpath as pindaoname from ccvms_channel ";
            var pindaodt = GetDTBySql(pindaosql);

            sql =string.Format("select * from ccvms_video where vid >{0}-2000 order by vid desc",maxid);
            dt = db.GetdataTableBySql(sql); 
            var xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><document><webSite>http://sjzyingyuan.com/</webSite><webMaster>804801300@qq.com</webMaster><updatePeri>60</updatePeri>";
            foreach (DataRow row in dt.Rows)
            {
                var title = row["title"].ToString();
                var href="";
                var pindaohtml = GetpindaoHtml(row, pindaodt);
                if (!string.IsNullOrEmpty(pindaohtml))
                    href = ConfigurationManager.AppSettings["wangzhi"] + "html/" + pindaohtml + "/" + GetDateTimeBy10int(Int64.Parse(row["createtime"].ToString())).ToString("yyyyMM") + @"/" + row["vid"].ToString() + ".html";
                else
                {
                    continue;
                }
                var tag =row["cid"].ToString() == "3"? "娱乐热点":"";
                var doc = row["description"].ToString();
                var imglink = ConfigurationManager.AppSettings["wangzhi"] + "attachments/" + row["networkpic"].ToString();
                var date = GetDateTimeBy10int(Int64.Parse(row["createtime"].ToString())).ToString("yyyy-MM-dd HH:mm");
                xml = xml + "<item><op>add</op>" +
                    "<title><![CDATA[" + title + "]]></title>" +
                    "<playLink><![CDATA[" + href + "]]></playLink>" +
                     "<imageLink><![CDATA[" + imglink + "]]></imageLink>" +
                     "<tag><![CDATA[" + tag + "]]></tag>" +
                     "<comment><![CDATA[" + doc + "]]></comment>" +
                     "<pubDate><![CDATA[" + date + "]]></pubDate>" +
                 "</item>";
            }
            xml += "</document>";
            return xml;

        }

        private string Creatxmlstring(string type,int begid,int endid)
        {
           
            var sql = "select max(vid) from ccvms_video";
            var dt = GetDTBySql(sql);
            if (dt.Rows.Count != 1)
                throw new ApplicationException("最大id为获取到");
            var maxid = int.Parse(dt.Rows[0][0].ToString());
            string pindaosql = "select cid as pindaoid,htmlpath as pindaoname from ccvms_channel ";
            var pindaodt = GetDTBySql(pindaosql);
            sql = string.Format("select * from ccvms_video where vid >{0}-2000", maxid);
            if (type == "google")
            {
                sql = string.Format("select * from ccvms_video where vid >{0} and vid<{1}", begid, endid);
            }
            dt = db.GetdataTableBySql(sql);
            var xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><document><webSite>http://sjzyingyuan.com/</webSite><webMaster>804801300@qq.com</webMaster><updatePeri>60</updatePeri>";
            if(type=="google")
            {                
                xml = "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:video=\"http://www.google.com/schemas/sitemap-video/1.1\">";
            }
            foreach (DataRow row in dt.Rows)
            {
                var title = row["title"].ToString();
                var href = "";
                var pindaohtml = GetpindaoHtml(row, pindaodt);
                if (!string.IsNullOrEmpty(pindaohtml))
                    href = ConfigurationManager.AppSettings["wangzhi"] + "html/" + pindaohtml + "/" + GetDateTimeBy10int(Int64.Parse(row["createtime"].ToString())).ToString("yyyyMM") + @"/" + row["vid"].ToString() + ".html";
                else
                {
                    continue;
                }
                var tag = row["cid"].ToString() == "3" ? "娱乐热点" : "";
                var doc = row["description"].ToString();
                var imglink = ConfigurationManager.AppSettings["wangzhi"] + "attachments/" + row["networkpic"].ToString();
                var date =GetDateTimeBy10int(Int64.Parse(row["createtime"].ToString())).ToString("yyyy-MM-dd HH:mm");//2012-07-07 15:50
                var videourl = row["videourl"].ToString();
                if (type == "google")
                {

                    xml = xml + "<url>" +
                         "<loc>" + href + "</loc>" +
                        "<video:video>"+
                        "<video:player_loc allow_embed=\"no\">"+videourl+"</video:player_loc>" +
                        "<video:title>" + title + "</video:title>" +
                        "<video:thumbnail_loc>" + imglink + "</video:thumbnail_loc>" +
                        "<video:description>" + doc + "</video:description>" +
                        "<video:rating>1.0</video:rating>" +
                        "<video:tag>" + tag + "</video:tag>" +
                            "</video:video>" +
                        "</url>";
                }
                else
                {
                    xml = xml + "<item><op>add</op>" +
                          "<title><![CDATA[" + title + "]]></title>" +
                          "<playLink><![CDATA[" + href + "]]></playLink>" +
                           "<imageLink><![CDATA[" + imglink + "]]></imageLink>" +
                           "<tag><![CDATA[" + tag + "]]></tag>" +
                           "<comment><![CDATA[" + doc + "]]></comment>" +
                           "<pubDate><![CDATA[" + date + "]]></pubDate>" +
                       "</item>";
                }
            }
             if (type == "google")
             {
                 xml+="</urlset>";
             }else{
                 xml += "</document>";
            
             }return xml;

        }
        private string GetpindaoHtml(DataRow row,DataTable pindaodt)
        {
            
            foreach (DataRow dr in pindaodt.Rows)
            {
                if (row["cid"].ToString()==dr["pindaoid"].ToString())
                {
                    return dr["pindaoname"].ToString();
                }
            }
            return "";
        }
        public DateTime GetDateTimeBy10int(Int64 mysqltime)
        {
            Int64 begtime = mysqltime * 10000000;//100毫微秒为单位,textBox1.text需要转化的int日期
            DateTime dt_1970 = new DateTime(1970, 1, 1, 8, 0, 0);
            long tricks_1970 = dt_1970.Ticks;//1970年1月1日刻度
            long time_tricks = tricks_1970 + begtime;//日志日期刻度
            DateTime dt = new DateTime(time_tricks);//转化为DateTime
            DateTime enddt = dt.Date;//获取到日期整数
            return enddt;
        }

        #endregion
        #region CreatHtml     
        /// <summary>
        /// 生成单页面静态
        /// </summary>
        public void CreatOneHtml(int id)
        {
            try
            {
                var url = string.Format("{0}index.php?r=generate&type=video&id={1}", ConfigurationManager.AppSettings["wangzhi"], id);
                GetPage(url, Encoding.UTF8);
                Err.writeInLog(string.Format("id:{0},生成html完成", id));
            }
            catch (Exception ex)
            {
                Err.writeInLog(string.Format("id:{0},生成html异常{1}",id,ex.Message));
            }

        }
        #endregion
        #region CreatXML
        public void CreatXML(string type,int begid,int endid)
        {

            StreamWriter sw = null;
            try
            {
                System.Text.Encoding code = System.Text.Encoding.GetEncoding("utf-8");
                string str = Creatxmlstring();             
                string mbPath = ConfigurationManager.AppSettings["xmladdress"];
                if (type == "google")
                {
                    str = Creatxmlstring("google", begid, endid);
                    mbPath = "e:/sjz/html/google.xml";
                }
                sw = new StreamWriter(mbPath, false, code);                
                sw.Write(str);
                sw.Flush();
            }
            catch (Exception ex)
            {
                Err.writeInLog(string.Format("生成XML异常{0}", ex.Message));
            }
            finally
            {
                if (sw != null)
                    sw.Close();
            }

        }
        public void CreatXML()
        {
           
            StreamWriter sw = null;
            try
            {
                System.Text.Encoding code = System.Text.Encoding.GetEncoding("utf-8");
                string str = Creatxmlstring();
                string mbPath = ConfigurationManager.AppSettings["xmladdress"];
                sw = new StreamWriter(mbPath, false, code);
                sw.Write(str);
                sw.Flush();
            }
            catch (Exception ex)
            {
                Err.writeInLog(string.Format("生成XML异常{0}", ex.Message));
            }
            finally
            {
                if(sw!=null)
                    sw.Close();
            }
           
        }
        #endregion
        #region 公共方法
        public int GetIntTime()
        {
            var month = DateTime.Now.Month.ToString();
            var day = DateTime.Now.Day.ToString();
            if (Convert.ToInt16(month) < 10)
            { month = 0 + month; }
            if (Convert.ToInt16(day) < 10)
            { day = 0 + day; }
            return int.Parse(DateTime.Now.Year.ToString() + month + day);
        }
        public DataTable GetDTBySql(string sql)
        {
            return db.GetdataTableBySql(sql);
        }
        public int ExecuteSql(string sql)
        {
            return db.ExecuteSql(sql);
        }
        public int ExecSqlAndReturnID(string strSQL, string[] strParams, object[] strValues)
        {
            return db.ExecSqlAndReturnID(strSQL, strParams, strValues);
        }
        public bool ExecuteUpdate(string strSql, string[] strParams, object[] strValues)
        {
           return db.ExecuteUpdate(strSql, strParams, strValues);
        }
        #endregion
        #region 返回整个页面流


        /// <summary>
        /// 返回整个页面str
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private string GetPage(string url, Encoding encoding)
        {
            //初始化新的request对象
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            //返回Internet资源的相应
            var webResponse = (HttpWebResponse)webRequest.GetResponse();
            //获取流
            var stream = webResponse.GetResponseStream();
            //读取编码
            var reader = new StreamReader(stream, encoding);
            //整个页面内容
            var content = reader.ReadToEnd();
            reader.Close();
            webResponse.Close();
            return content;
        }
        /// <summary>
        /// 返回整个页面str
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private string GetHtmlCode(string url)
        {
            string htmlCode;
            var webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            webRequest.Timeout = 30000;
            webRequest.Method = "GET";
            webRequest.UserAgent = "Mozilla/4.0";
            webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            var webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
            if (webResponse.ContentEncoding.ToLower() == "gzip")//如果使用了GZip则先解压
            {
                using (var streamReceive = webResponse.GetResponseStream())
                {
                    using (var zipStream =
                        new System.IO.Compression.GZipStream(streamReceive, System.IO.Compression.CompressionMode.Decompress))
                    {
                        using (var sr = new System.IO.StreamReader(zipStream, Encoding.UTF8))
                        {
                            htmlCode = sr.ReadToEnd();
                        }
                    }
                }
            }
            else
            {
                using (var streamReceive = webResponse.GetResponseStream())
                {
                    using (var sr = new System.IO.StreamReader(streamReceive, Encoding.UTF8))
                    {
                        htmlCode = sr.ReadToEnd();
                    }
                }
            }

            return htmlCode;
        }
        #endregion

    }
}
